package com.jinke.api.modules.third.myus56.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jinke.api.common.api.CommonResult;
import com.jinke.api.common.util.CommonUtil;
import com.jinke.api.common.util.Global;
import com.jinke.api.modules.app.enums.BalanceLogType;
import com.jinke.api.modules.app.enums.OrderStatus;
import com.jinke.api.modules.app.enums.OrderType;
import com.jinke.api.modules.app.enums.ValidateStatus;
import com.jinke.api.modules.app.model.Order;
import com.jinke.api.modules.app.model.OrderParcel;
import com.jinke.api.modules.app.response.CreateLabel2Response;
import com.jinke.api.modules.app.service.IUserOrderTaskService;
import com.jinke.api.modules.app.service.OrderParcelService;
import com.jinke.api.modules.app.service.OrderService;
import com.jinke.api.modules.app.service.UserRechargeService;
import com.jinke.api.modules.app.util.MathUtil;
import com.jinke.api.modules.app.util.OssUtil;
import com.jinke.api.modules.base.service.ThirdService;
import com.jinke.api.modules.third.ezeeship.model.request.EstimateRateRequest;
import com.jinke.api.modules.third.ezeeship.model.response.CreateLabelResponse;
import com.jinke.api.modules.third.ezeeship.model.response.EstimateRateResponse;
import com.jinke.api.modules.third.ezeeship.service.EzeeShipService;
import com.jinke.api.modules.third.myus56.model.response.*;
import com.jinke.api.modules.third.myus56.service.IMyus56Service;
import com.jinke.api.modules.third.myus56.util.Myus56Utils;
import com.jinke.api.modules.ums.model.Channel;
import com.jinke.api.modules.ums.model.UmsAdmin;
import com.jinke.api.modules.ums.service.*;
import com.jinke.api.modules.ums.vo.UserChannelVO;
import com.jinke.api.security.util.ApiUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author huang
 * @data 2024-05-17
 */
@Slf4j
@Service
public class Myus56ServiceImpl implements IMyus56Service {
    @Resource
    private ThirdService thirdService;
    @Resource
    private ChannelService channelService;
    @Resource
    private EzeeShipService ezeeShipService;
    @Resource
    private OrderParcelService orderParcelService;
    @Resource
    private UmsAdminService umsAdminService;
    @Resource
    private Myus56Utils myus56Utils;
    @Resource
    private OssUtil ossUtil;
    @Resource
    private OrderService orderService;
    @Resource
    private UserRechargeService userRechargeService;
    @Resource
    private IApiLogService iApiLogService;
    @Resource
    private IUserOrderTaskService iUserOrderTaskService;

    @Resource
    private ICancelApiLogService iCancelApiLogService;
    @Resource
    private IPreSucLogService iPreSucLogService;



    @Override
    public CommonResult estimateRate(EstimateRateRequest request) {
        Integer  userId = ApiUserUtil.getUserId();
        return estimateRate(request, userId);
    }

    @Override
    public CommonResult estimateRate(EstimateRateRequest request, Integer userId) {
        //生成给第三方的订单编号
        String orderNumber = CommonUtil.getOrderNo();
        //查询渠道code
        Channel channel = channelService.getById(request.getChannelId());
        BigDecimal rate;
        try {
            rate = getPrice(request, channel.getChannelCode(), userId, orderNumber);
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
        if (rate.compareTo(new BigDecimal("0")) > 0) {
            EstimateRateResponse.Data newData = new EstimateRateResponse.Data();
            newData.setRate(rate);
            return CommonResult.success(newData);
        }
        return CommonResult.failed("系统异常,请联系管理人员");
    }

    /**
     * 获取预估金额
     * @param request
     * @param channelCode
     * @param userId
     * @param orderNumber
     * @return
     */
    private BigDecimal getPrice(EstimateRateRequest request, String channelCode, Integer userId, String orderNumber) {
        BigDecimal rate = new BigDecimal("0");
        //发送估价请求
        String result = myus56Utils.getPrice(request, channelCode, orderNumber);
//          String result = "{\n" +
//                "    \"code\": 200,\n" +
//                "    \"message\": \"OK\",\n" +
//                "    \"data\": [\n" +
//                "        {\n" +
//                "            \"no\": \"112-2255912-9234603_f8c1\",\n" +
//                "            \"children\": [\n" +
//                "                {\n" +
//                "                    \"error\": \"\",\n" +
//                "                    \"product\": \"AJ\",\n" +
//                "                    \"chargeAmount\": 0,\n" +
//                "                    \"chargeWeight\": 0,\n" +
//                "                    \"chargeWeightUnit\": \"LBS\"\n" +
//                "                }\n" +
//                "            ]\n" +
//                "        }\n" +
//                "    ]\n" +
//                "}";


        /*
        总重量已低于最小下限 (当前: 32.739LBS < 最小下限: 200.000LBS)
        String error = "{\n" +
                "    \"code\": 400,\n" +
                "    \"message\": \"第 1 件包裹 第 1 个 参考号 只能由字母、数字、短划线(-)和下划线(_)组成。\"\n" +
                "}";*/
        if (StringUtils.isNotEmpty(result)) {
            JSONObject jsonObject = JSON.parseObject(result);
            Integer code = jsonObject.getInteger("code");
            if (code == 400) {
                throw new RuntimeException(jsonObject.getString("message"));
            }
            Myus56GetPriceResponse response = JSONUtil.toBean(result, Myus56GetPriceResponse.class);
            GetPriceChildren children = response.getData().get(0).getChildren().get(0);
            //存在错误信息。说明估价失败
            if (StringUtils.isNotEmpty(children.getError())) {
                throw new RuntimeException(children.getError());
            }
            BigDecimal price = children.getChargeAmount();
            rate = thirdService.calcRate(userId, request.getUserChannelVO(), price);
        }
        return rate;
    }

    @Override
    public CommonResult createLabel(EstimateRateRequest request) {
        Integer userId = ApiUserUtil.getUserId();
        return createLabel(request, userId);
    }

    @Override
    public CommonResult createLabel(EstimateRateRequest request, Integer userId) {
        if (StringUtils.isBlank(request.getOrderNO())) {
            String orderNo = CommonUtil.getOrderNo();
            request.setOrderNO(orderNo);
        }
        if (request.getTo().getStateCode().equals("California")){
            request.getTo().setStateCode("ca");
        }
        if (request.getFrom().getStateCode().equals("California")){
            request.getFrom().setStateCode("ca");
        }


        UserChannelVO userChannelVO = request.getUserChannelVO();
        Channel channel = userChannelVO.getChannel();
        //给住宅地址的设置channel
        ezeeShipService.fillResidential(request, userId);
        //预估订单金额
        BigDecimal rate;
        try {
            //获取预估金额
            rate = getPrice(request, channel.getChannelCode(), userId, request.getPlatformNo());
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
        UmsAdmin umsAdmin = umsAdminService.getById(userId);
        if (rate.compareTo(new BigDecimal("0")) == 0 && ObjectUtils.isEmpty(umsAdmin)) {
            return CommonResult.failed("数据有误");
        }
        //计算当前用户的可支配金额
        BigDecimal totalAmount = umsAdmin.getBalance().add(umsAdmin.getCreditBalance());
        if (totalAmount.compareTo(rate) < 0) {
            return CommonResult.failed("Insufficient Balance");
        }
        Channel channel1 = channelService.getById(request.getChannelId());
        //下单
        String result =    myus56Utils.createOrder(request, channel1.getChannelCode(),request.getPlatformNo());
        if (StringUtils.isNotEmpty(result)) {
            CreateOrder createOrder = JSONUtil.toBean(result, CreateOrder.class);
            //code 400 预创建订单失败了
            if (createOrder.getCode() == 400) {
                return CommonResult.failed(createOrder.getMessage());
            }
            CreateData data = createOrder.getData().get(0);
            Integer status = data.getStatus();
            if (CollectionUtil.isNotEmpty(data.getErrors())) {
                return CommonResult.failed(String.join(",", data.getErrors()));
            }
            if (status < 0) {
                return CommonResult.failed(ErrorEnums.defaultEnum(status).getDesc());
            }
            //调用轮训接口查询订单详情(调用30次)
            for (int i = 0; i < 10; i++) {
                try {
                    // 尝试等待2秒
                    TimeUnit.SECONDS.sleep(2);
                    //查订单状态
                    String statusResponse =    myus56Utils.getStatus(data.getRequest_id());

                    if (StringUtils.isNotEmpty(statusResponse)) {
                        iApiLogService.saveApiLog(statusResponse, request.getOrderNO(),"myus56-查询状态");
                        JSONObject jsonObject = JSON.parseObject(statusResponse);
                        Integer code = jsonObject.getInteger("code");
                        String dataString = jsonObject.getString("data");
                        CreateData createOrders = JSONUtil.toBean(dataString, CreateData.class);
                        //code 400 预创建订单失败了
                        if (code == 400) {
                            return CommonResult.failed(String.join(",", createOrders.getErrors()));
                        }
                        status = createOrders.getStatus();
                        //预报订单成功
                        if (status == 10) {
                            break;
                        }
                        //预报失败直接返回失败原因
                        if (status < 0) {
                            return CommonResult.failed(String.join(",", createOrders.getErrors()));
                        }
                    }
                } catch (Exception e) {
                    log.info("===My56===查询订单详情异常，{}", e.getMessage());
                }
            }
            //30次调用之后还未下单成功 不再继续，此处不直接取消 由新任务取消，因为可能在第三方为预成功状态
            if (status != 10) {
                log.error("30次调用myus56之后还未下单成功，取消订单改成进新表");
                 //   myus56Utils.deleteOrder(platformNO);
                try {

                    iCancelApiLogService.saveCancelApiLog(request.getPlatformNo(),request.getOrderNO(),userId);
                }catch (Exception e){
                    log.info("-------保存到取消订单表错误---------"+e.getMessage());
                }
                return CommonResult.failed("订单响应时间过长，下单失败");
            }
            //获取订单详情-下单成功,调用订单详情接口，面单下载接口(可能存在延迟出单情况，需要重复获取)
            Myus56FindResponse orderInfo = getOrderInfo15Times(request.getOrderNO(),request.getPlatformNo());
            //获取面单信息
            String labelUrl = getOrderDownLoad15Time(request.getOrderNO(),request.getPlatformNo());
            if (ObjectUtils.isEmpty(orderInfo) || StringUtils.isEmpty(labelUrl)) {
                try {
                    //调用订单删除接口
                    iCancelApiLogService.saveCancelApiLog(request.getPlatformNo(), request.getOrderNO(), userId);
                } catch (Exception e) {
                    log.info("-------保存到取消订单表错误---------" + e.getMessage());
                }
                return CommonResult.failed("服务商延迟严重，稍后再试");
            }
            BigDecimal charge_amount = orderInfo.getData().getCharge_amount();
            //溢价费用
            BigDecimal afterRate = thirdService.calcRate(userId, request.getUserChannelVO(), charge_amount);
            //扣减用户余额
            if (afterRate.compareTo(BigDecimal.ZERO) > 0) {
                log.info(request.getOrderNO() + "准备扣钱" + afterRate);
                userRechargeService.decrTransfer(userId, afterRate, BalanceLogType.CONSUME, "寄件", request.getOrderNO(), request.getObjectId(), channel,null);

            }

            //上传pdf文件
            ossUtil.upload("pdf", data.getRequest_id() + ".pdf", labelUrl);
            String newPdfUrl = Global.PRINT_LABEL_API + data.getRequest_id();
            //保存订单信息
            Order order = saveOrUpdateOrder(request, userId, umsAdmin, charge_amount,  data.getRequest_id(), newPdfUrl,afterRate );
            //定时任务表插入一条数据
            iUserOrderTaskService.saveByOrderId(order.getId());
            //修改包裹信息
            updateParcel(order, orderInfo);

            //组装返回信息
            CreateLabelResponse.Data newCreateLabelResponseData = getData(data.getRequest_id(), orderInfo, newPdfUrl, order.getRate());
            return CommonResult.success(newCreateLabelResponseData);
        }
        return CommonResult.failed("下单失败");
    }


    /**
     * 重构页面批量下单
     * @param request
     * @param userId
     * @return
     */
    @Override
    public CommonResult createLabelForPage(EstimateRateRequest request, Integer userId) {
        if (request.getTo().getStateCode().equals("California")){
            request.getTo().setStateCode("ca");
        }
        if (request.getFrom().getStateCode().equals("California")){
            request.getFrom().setStateCode("ca");
        }
        String platformNO = CommonUtil.getOrderNo();
        if (ObjectUtils.isEmpty(userId)) {
            userId = ApiUserUtil.getUserId();
        }
        if (StringUtils.isBlank(request.getOrderNO())) {
            String orderNo = CommonUtil.getOrderNo();
            request.setOrderNO(orderNo);
        }
        UserChannelVO userChannelVO = request.getUserChannelVO();
        Channel channel = userChannelVO.getChannel();
        //给住宅地址的设置channel
        ezeeShipService.fillResidential(request, userId);
        //预估订单金额
        BigDecimal rate;
        try {
            //获取预估金额
            rate = getPrice(request, channel.getChannelCode(), userId, platformNO);
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
        UmsAdmin umsAdmin = umsAdminService.getById(userId);
        if (rate.compareTo(new BigDecimal("0")) == 0 && ObjectUtils.isEmpty(umsAdmin)) {
            return CommonResult.failed("数据有误");
        }
        //计算当前用户的可支配金额
        BigDecimal totalAmount = umsAdmin.getBalance().add(umsAdmin.getCreditBalance());
        if (totalAmount.compareTo(rate) < 0) {
            return CommonResult.failed("Insufficient Balance");
        }
        Channel channel1 = channelService.getById(request.getChannelId());
        //下单
        String result =    myus56Utils.createOrder(request, channel1.getChannelCode(), platformNO);

        if (StringUtils.isNotEmpty(result)) {
            CreateOrder createOrder = JSONUtil.toBean(result, CreateOrder.class);
            //code 400 预创建订单失败了
            if (createOrder.getCode() == 400) {
                return CommonResult.failed(createOrder.getMessage());
            }
            CreateData data = createOrder.getData().get(0);
            Integer status = data.getStatus();
            if (CollectionUtil.isNotEmpty(data.getErrors())) {
                return CommonResult.failed(String.join(",", data.getErrors()));
            }
            if (status < 0) {
                return CommonResult.failed(ErrorEnums.defaultEnum(status).getDesc());
            }
            //保存订单信息
             saveOrUpdateOrderBatch(request, userId,umsAdmin,    data.getRequest_id(),platformNO);

             //加预报成功表
            log.info("预报成功加入预报成功表{}",request.getOrderNO());
            iPreSucLogService.saveLog(channel.getId(),userId,data.getRequest_id(),request.getOrderId(),request.getOrderNO());
            return CommonResult.success();
        }
        return CommonResult.failed("下单失败");


    }
    /**
     * 保存或修改订单信息
     *
     * @param request   请求参数
     * @param userId    用户id
     * @param umsAdmin  用户信息
     * @param request_id      预下单结果
     * @return 订单
     */
    private Order saveOrUpdateOrderBatch(EstimateRateRequest request,
                                         Integer userId, UmsAdmin umsAdmin,
                                         String request_id
                                     ,String platformno) {
        //覆盖订单信息
        Order order = new Order();
        BeanUtils.copyProperties(request, order);
        order.setId(request.getOrderId());
        order.setUserId(userId);
        order.setErrMsg("");
        order.setOrderNo(request.getOrderNO());
        if (ObjectUtils.isNotEmpty(umsAdmin.getSellerId())) {
            order.setSellerId(umsAdmin.getSellerId());
        }
        UserChannelVO userChannelVO = request.getUserChannelVO();
        Channel channel = userChannelVO.getChannel();

        order.setChannelId(channel.getId());

        //objectId(这里存放第三方任务id)
        order.setObjectId(request_id);
        order.setOrderType(OrderType.BAAPI);
        order.setStatus(OrderStatus.ORDER_PRE_SUC.getValue());


        try {
            order.setReference(request.getExtra().getReference());
            order.setReference2(request.getExtra().getReference2());
        }catch (Exception e){
            log.error("设置reference出错了");
        }
        order.setPlatformNo(platformno);

        //更新地址信息
        order.setFromCity(request.getFrom().getCity());
        order.setFromEmail(request.getFrom().getEmail());
        order.setFromCompany(request.getFrom().getCompany());
        order.setFromPhone(request.getFrom().getPhone());
        order.setFromAddressLine2(request.getFrom().getAddressLine2());
        order.setFromAddressLine1(request.getFrom().getAddressLine1());
        order.setFromCountryCode(request.getFrom().getCountryCode());
        order.setFromZipCode(request.getFrom().getZipCode());
        order.setFromPersonName(request.getFrom().getPersonName());
        order.setFromStateCode(request.getFrom().getStateCode());

        EstimateRateRequest.Address requestTo = request.getTo();
        order.setToCity(requestTo.getCity());
        order.setToEmail(requestTo.getEmail());
        order.setToCompany(requestTo.getCompany());
        order.setToPhone(requestTo.getPhone());
        order.setToAddressLine2(requestTo.getAddressLine2());
        order.setToAddressLine1(requestTo.getAddressLine1());
        order.setToCountryCode(requestTo.getCountryCode());
        order.setToZipCode(requestTo.getZipCode());
        order.setToPersonName(requestTo.getPersonName());
        order.setToStateCode(requestTo.getStateCode());

        if (BooleanUtil.isTrue(requestTo.getIsValid())) {
            order.setValidateStatus(ValidateStatus.defaultEnum(requestTo.getIsResidential()));
        } else {
            order.setValidateStatus(ValidateStatus.UN_VALIDATE);
        }
        //这里有没有记录rate 和成本
        orderService.saveOrUpdate(order);
        return order;
    }


    /**
     * 看预报成功是否转真
     * @param request_id
     * @param request
     * @param userId
     * @param orderNumber
     * @return
     */
    public CommonResult ifPreSuccessToTrue(String request_id, EstimateRateRequest request,
                                           Integer userId,
                                           BigDecimal rate, String orderNumber
                                             , String platformNo) {
        int status = 0;
        UmsAdmin user = umsAdminService.getOne(new LambdaQueryWrapper<UmsAdmin>().eq(UmsAdmin::getId, userId));
        try {

            //查订单状态
            String statusResponse =    myus56Utils.getStatus(request_id);

            if (StringUtils.isNotEmpty(statusResponse)) {
                iApiLogService.saveApiLog(statusResponse, request.getOrderNO(),"myus56-状态");
                JSONObject jsonObject = com.alibaba.fastjson.JSON.parseObject(statusResponse);
                Integer code = jsonObject.getInteger("code");
                String dataString = jsonObject.getString("data");
                CreateData createOrders = JSONUtil.toBean(dataString, CreateData.class);
                //code 400 预创建订单失败了
                if (code == 400) {
                    return CommonResult.failed(String.join(",", createOrders.getErrors()));
                }
                status = createOrders.getStatus();

                //预报失败直接返回失败原因
                if (status < 0) {
                    return CommonResult.failed(String.join(",", createOrders.getErrors()));
                }
            }
        } catch (Exception e) {
            log.info("===My56===查询订单详情异常，{}", e.getMessage());
            return CommonResult.failed("查询订单详情异常");
        }

        if (status == 10) {
            log.info("===My56===预报订单成功{}", orderNumber);
            //获取订单详情
            Myus56FindResponse orderInfo = getOrderInfoOneTime(request.getOrderNO(), platformNo);
            if (ObjectUtils.isEmpty(orderInfo)) {
                log.info("{}===My56===获取面单返回非200", orderNumber);
                LocalDateTime now = LocalDateTime.now();
                //状态已经成功就不取消 此返回会记到pre_success表的msg中
                return CommonResult.failed("订单状态预报订单但获取订单详情返回存在延时，请稍后再试" + now);
            }
            //获取面单信息
            String labelUrl = getOrderDownLoadOneTime(request.getOrderNO(), platformNo);
            if (StringUtils.isEmpty(labelUrl)) {
                //状态已经成功就不取消
                return CommonResult.failed("订单详情返回成功但获取面单信息返回存在延时，请稍后再试");
            }
            //上传pdf文件
            ossUtil.upload("pdf", request_id + ".pdf", labelUrl);
            String newPdfUrl = Global.PRINT_LABEL_API + request_id;

            //更新订单信息
            Order order = updateOrderAftersuc(request,  newPdfUrl,orderInfo.getData().getCharge_amount(),user);
            //定时任务表插入一条数据
            iUserOrderTaskService.saveByOrderId(order.getId());
            //修改包裹信息
            updateParcel(order, orderInfo);
            log.info("批量下单环洋rate"+rate);
            log.info("批量下单环洋rate 祥情返回的"+order.getRate());
            rate=order.getRate();
            if (rate.compareTo(BigDecimal.ZERO) > 0) {
                userRechargeService.decrTransfer(userId, rate, BalanceLogType.CONSUME, "寄件", order.getOrderNo(), order.getObjectId(), null,null);
            }
            //组装返回信息 批量可以不要
            CreateLabelResponse.Data newCreateLabelResponseData = getData(request_id, orderInfo, newPdfUrl, rate);
            return CommonResult.success(newCreateLabelResponseData);
        }
        return CommonResult.failed("====订单状态不成功========" + status);
    }

    /**
     * 组装返回信息
     * @param objectId
     * @param orderInfo
     * @param newPdfUrl
     * @param rate
     * @return
     */
    @NotNull
    private CreateLabelResponse.Data getData(String objectId, Myus56FindResponse orderInfo, String newPdfUrl,BigDecimal rate) {
        CreateLabelResponse.Data newCreateLabelResponseData = new CreateLabelResponse.Data();
        newCreateLabelResponseData.setRate(rate);

        CreateLabel2Response.FeeDetail newFeeDetail = new CreateLabel2Response.FeeDetail();
        newFeeDetail.setBaseRate(rate);
        newCreateLabelResponseData.setFeeDetail(newFeeDetail);

        newCreateLabelResponseData.setRate(rate);
        newCreateLabelResponseData.setStatus(1);
        newCreateLabelResponseData.setCreateTime(LocalDateTime.now());
        newCreateLabelResponseData.setObjectId(objectId);
        newCreateLabelResponseData.setPdfUrl(newPdfUrl);
        newCreateLabelResponseData.setTrackingNumber(orderInfo.getData().getChildren().stream().map(Myus56FindDataChildrenResponse::getTracking_number).collect(Collectors.toList()));
        String labelUrl = Global.PRINT_LABEL_API + objectId;
        newCreateLabelResponseData.setLabelUrl(Collections.singletonList(labelUrl));
        return newCreateLabelResponseData;
    }

    /**
     * 删除原包裹信息，保存新的包裹信息
     *
     * @param order     订单信息
     * @param orderInfo 第三方订单详情返回结果
     */
    @Transactional
    public void updateParcel(Order order, Myus56FindResponse orderInfo) {
        String pdfUrl = order.getPdfUrl();
        Integer userId = order.getUserId();
        Integer orderId = order.getId();

        List<Myus56FindDataChildrenResponse> children = orderInfo.getData().getChildren();
        List<OrderParcel> parcelList = children.stream().map(c -> {
            OrderParcel op = new OrderParcel();
            op.setUserId(userId);
            op.setOrderId(orderId);
            op.setWeight(c.getWeight().toString());
            op.setWidth(c.getWidth().toString());
            op.setHeight(c.getHeight().toString());
            op.setLength(c.getLength().toString());
            op.setMassUnit("kg");
            op.setDistanceUnit("cm");
            op.setTrackingNumber(c.getTracking_number());
            op.setLabelUrl(pdfUrl);
            op.setTrackingUrl(pdfUrl);
            return op;
        }).collect(Collectors.toList());
        orderParcelService.remove(new LambdaQueryWrapper<OrderParcel>().eq(OrderParcel::getOrderId, orderId));
        orderParcelService.saveBatch(parcelList);
    }

    /**
     * 保存或修改订单信息
     *
     * @param request   请求参数
     * @param userId    用户id
     * @param umsAdmin  用户信息
     * @param    originFee 第三方平台原始费用
     * @param request_id      预下单结果
     * @param newPdfUrl 新面单pdfUrl
     * @param afterRate
     * @return 订单
     */
    private Order saveOrUpdateOrder(EstimateRateRequest request, Integer userId, UmsAdmin umsAdmin,
                                    BigDecimal originFee, String request_id, String newPdfUrl,
                                    BigDecimal afterRate) {
        //覆盖订单信息
        Order order = new Order();
        BeanUtils.copyProperties(request, order);
        order.setId(request.getOrderId());
        order.setUserId(userId);
        order.setErrMsg("");
        order.setOrderNo(request.getOrderNO());
        if (ObjectUtils.isNotEmpty(umsAdmin.getSellerId())) {
            order.setSellerId(umsAdmin.getSellerId());
        }



        order.setOriginFee(originFee);
        order.setRate(afterRate);
        //计算保证金
        BigDecimal subEarnestBalance = MathUtil.formatBigDecimal(afterRate.multiply(umsAdmin.getEarnestRate()));
        order.setEarnest(subEarnestBalance);

        //objectId(这里存放第三方任务id)
        order.setObjectId(request_id);
        order.setPdfUrl(newPdfUrl);
        order.setStatus(OrderStatus.RECENT.getValue());
        order.setCreateTime(LocalDateTime.now());


        order.setReference(request.getExtra().getReference());
        order.setReference2(request.getExtra().getReference2());

        //更新地址信息
        order.setFromCity(request.getFrom().getCity());
        order.setFromEmail(request.getFrom().getEmail());
        order.setFromCompany(request.getFrom().getCompany());
        order.setFromPhone(request.getFrom().getPhone());
        order.setFromAddressLine2(request.getFrom().getAddressLine2());
        order.setFromAddressLine1(request.getFrom().getAddressLine1());
        order.setFromCountryCode(request.getFrom().getCountryCode());
        order.setFromZipCode(request.getFrom().getZipCode());
        order.setFromPersonName(request.getFrom().getPersonName());
        order.setFromStateCode(request.getFrom().getStateCode());

        EstimateRateRequest.Address requestTo = request.getTo();
        order.setToCity(requestTo.getCity());
        order.setToEmail(requestTo.getEmail());
        order.setToCompany(requestTo.getCompany());
        order.setToPhone(requestTo.getPhone());
        order.setToAddressLine2(requestTo.getAddressLine2());
        order.setToAddressLine1(requestTo.getAddressLine1());
        order.setToCountryCode(requestTo.getCountryCode());
        order.setToZipCode(requestTo.getZipCode());
        order.setToPersonName(requestTo.getPersonName());
        order.setToStateCode(requestTo.getStateCode());
        order.setOrderType(OrderType.API);

        if (BooleanUtil.isTrue(requestTo.getIsValid())) {
            order.setValidateStatus(ValidateStatus.defaultEnum(requestTo.getIsResidential()));
        } else {
            order.setValidateStatus(ValidateStatus.UN_VALIDATE);
        }
        orderService.saveOrUpdate(order);
        return order;
    }
    /**
     * 更新订单信息
     *
     * @param request   请求参数
     * @param originFee
     * @param user
     * @return 订单
     */
    private Order updateOrderAftersuc(EstimateRateRequest request,

                                      String labelPdf, BigDecimal originFee, UmsAdmin user) {
        //覆盖订单信息
        Order order = new Order();
        BeanUtils.copyProperties(request, order);
        order.setId(request.getOrderId());

        //溢价费用
        BigDecimal rate = thirdService.calcRate(user.getId(), request.getUserChannelVO(), originFee);
        //成本价
        order.setOriginFee(originFee);
        order.setRate(rate);
        //计算保证金
        BigDecimal subEarnestBalance = MathUtil.formatBigDecimal(rate.multiply(user.getEarnestRate()));
        order.setEarnest(subEarnestBalance);


        order.setErrMsg("");
        order.setOrderType(OrderType.BAAPI);
        order.setPdfUrl(labelPdf);
        order.setStatus(OrderStatus.RECENT.getValue());
        order.setCreateTime(LocalDateTime.now());

        orderService.updateById(order);
        return order;
    }

    /**
     * 获取面单信息15次
     *
     * @param orderNo 平台订单编号
     */
    private String getOrderDownLoad15Time(String orderNo, String platformNo) {
        try {
            for (int i = 0; i < 15; i++) {
                TimeUnit.SECONDS.sleep(2);
                String orderDownLoadOnce = this.getOrderDownLoadOneTime(orderNo, platformNo);
                if (orderDownLoadOnce != null) {
                    return orderDownLoadOnce;
                }
            }
        } catch (Exception e) {
            log.info("-----------轮训获取订单详情异常-----------,{}", e.getMessage());
        }
        return null;
    }

    /**
     * 环洋下载面单
     * @param orderNo
     * @param platformNo
     * @return
     */
    private String getOrderDownLoadOneTime(String orderNo, String platformNo) {
        //下载面单
        String result =    myus56Utils.download(platformNo);
        if (StringUtils.isNotEmpty(result)) {
            //记日志
            iApiLogService.saveApiLog(result, orderNo,"myus56-下载面单");
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer code = jsonObject.getInteger("code");
            if (code == 200) {
                JSONObject data = jsonObject.getJSONObject("data");
                return data.getString("url");
            }
        }
        return null;
    }

    /**
     * 获取订单详情15次
     *
     * @param orderNo 订单编号
     */
    private Myus56FindResponse getOrderInfo15Times(String orderNo, String orderNumber) {
        try {
            TimeUnit.SECONDS.sleep(2);

            for (int i = 0; i < 15; i++) {
                Myus56FindResponse orderInfoOnece = this.getOrderInfoOneTime(orderNo, orderNumber);
                if (orderInfoOnece != null) {
                    return orderInfoOnece;
                }
            }
        } catch (Exception e) {
            log.info(orderNumber + "-----------轮训获取订单详情异常-----------,{}", e.getMessage());
        }
        return null;
    }

    /**
     * 查询Myus56订单详情
     * @param orderNo
     * @param platformno
     * @return
     */
    private Myus56FindResponse getOrderInfoOneTime(String orderNo, String platformno) {
        //查询Myus56订单详情
        String request =    myus56Utils.find(platformno);
        if (StringUtils.isNotEmpty(request)) {
            iApiLogService.saveApiLog(request, orderNo,"myus56-订单详情");
            Integer code = JSONObject.parseObject(request).getInteger("code");
            if (code == 200) {
                return JSONUtil.toBean(request, Myus56FindResponse.class);
            }
        }

        return null;
    }

    @Override
    public CommonResult getLabel(String objectId) {
        Integer userId = ApiUserUtil.getUserId();

        return getLabel(objectId, userId);
    }

    @Override
    public CommonResult getLabel(String objectId, Integer userId) {
        Order order = orderService.lambdaQuery().select(Order::getPdfUrl, Order::getPlatformNo, Order::getId, Order::getOrderNo).eq(Order::getObjectId, objectId).one();

        String pdfUrl = order.getPdfUrl();
        if (StringUtils.isBlank(pdfUrl)) {
            //查询为空则从接口下载
            pdfUrl = this.getOrderDownLoadOneTime(order.getOrderNo(), order.getPlatformNo());
        }

        CreateLabelResponse.Data newCreateLabelResponseData = new CreateLabelResponse.Data();
        newCreateLabelResponseData.setObjectId(objectId);
        newCreateLabelResponseData.setPdfUrl(pdfUrl);
        newCreateLabelResponseData.setLabelUrl(Arrays.asList(pdfUrl));

        return CommonResult.success(newCreateLabelResponseData);
    }

    @Override
    public CommonResult cancelLabel(String objectId,String orderNo) {
        Order order = orderService.lambdaQuery().select(Order::getPlatformNo, Order::getId, Order::getOrderNo).eq(Order::getObjectId, objectId).one();
        if (ObjectUtils.isNotEmpty(order)) {
            String result = myus56Utils.cancleOrder(orderNo, order.getPlatformNo());
            if (ObjectUtils.isNotEmpty(result)) {

                JSONObject jsonObject = JSONObject.parseObject(result);
                Integer code = jsonObject.getInteger("code");
                return code == 200 ? CommonResult.success() : CommonResult.failed(jsonObject.getString("message"));
            }
        }
        return CommonResult.failed("取消订单失败,未查询到对应订单信息");
    }

    @Override
    public CommonResult tracking(String trackingNumber) {
        return null;
    }

    @Override
    public CommonResult cancelInsurance(String insuranceId) {

        return CommonResult.success();
    }
}
